<?php

namespace app\worker;

use app\logic\SendMessageLog;
use app\logic\User;
use Codeages\Plumber\AbstractWorker;
use Codeages\Plumber\Queue\Job;

class AddSendLogWorker extends AbstractWorker
{
    public function execute(Job $job): ?string
    {
        $this->logger->info("job ", [$job->getBody()]);
        $job->setDelay(100);
        try {
            list($templateId, $userOpenId) = explode(':', $job->getBody());

            $user = $this->getUserLogic()->getUserByOpenId($userOpenId);

            if (empty($user)) {
                return null;
            }

            $this->getSendLogLogic()->createLog([
                'user_id' => $user['id'],
                'template_id' => $templateId,
                'status' => 'succeed'
            ]);

            return self::FINISH;
        } catch (\Exception $e) {
            $this->logger->error("execute job #{$job->getId()}", [$e->getMessage()]);
            throw $e;
            return self::BURY;
        }
    }

    /**
     * @return User
     */
    protected function getUserLogic(): User
    {
        return app('logic')->logic('User');
    }

    /**
     * @return SendMessageLog
     */
    protected function getSendLogLogic(): SendMessageLog
    {
        return app('logic')->logic('SendMessageLog');
    }
}
